package com.lanou3g.springmvc.web;

import com.lanou3g.springmvc.bean.User;
import com.lanou3g.springmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.net.URI;
import java.util.List;

@Controller
public class HelloController {

    @Autowired
    private UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    /*@RequestMapping("/index")
    public String index() {
        System.out.println("index");
        return "index2";
    }*/

    @RequestMapping("/hello")
    public String toHelloPage(@RequestParam String message, @RequestHeader("User-Agent") String userAgent, Model model) {
        model.addAttribute("msg", message);
        model.addAttribute("userAgent", userAgent);
        return "hello_springmvc";
    }

    @RequestMapping("/hello_world")
    public String helloWorld(Model model) {
        model.addAttribute("msg", "hello world");
        return "hello_springmvc";
    }

    @RequestMapping("/userlist")
    public String index2() {
        System.out.println("/userlist方法");
        return "index2";
    }

    @RequestMapping("/userList")
    public String toUserList(Model model) {
        List<User> userList = userService.queryUser();
        model.addAttribute("userList", userList);
        return "userlist"; //直接返回逻辑视图名，实际上使用的是forward的方式

//        return "forward:userlist";  //添加forward前缀以后，返回的字符串，不会交给视图解析器去解析
//        return new InternalResourceView("userlist");    //这种直接返回View的方式也可以完成forward，等效于上面的代码

//        return "redirect:/userlist.jsp"; //添加redirect前缀，变成重定向，地址栏会变。但是返回值也不走视图解析器
//        return new RedirectView("/userlist.jsp");
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/test_private")
    public String toPrivateTestPage() {
        return "/WEB-INF/page/test";
    }

    @RequestMapping("/baidu")
    public String baidu(Model model) {

        String result = restTemplate.getForObject(URI.create("http://www.baidu.com"), String.class);

        model.addAttribute("msg", result);

        return "hello_springmvc";
    }

    @RequestMapping("/hello/redirect_param")
    public String redirect_param(RedirectAttributes redirectAttributes) {
        redirectAttributes.addAttribute("sname", "张三");
        return "redirect:/hello_springmvc.jsp";
    }

}
